package net.gagnat.android.trackit.service;

import java.util.ArrayList;
import java.util.List;

import net.gagnat.android.trackit.domain.LogEntry;
import android.content.Context;

public class LogEntriesRepository {

	private static LogEntriesRepository logEntryListRepository = null;

	private LogEntryDbManager logEntryDbManager = null;

	private List<LogEntry> logEntries = new ArrayList<LogEntry>();

	public static LogEntriesRepository getInstance() {
		return logEntryListRepository;
	}

	/**
	 * Initializes the repository including instanciation of an arrayadapter.
	 * 
	 * @param context
	 *            The current context.
	 */
	public static LogEntriesRepository initialize(Context context) {
		if (logEntryListRepository == null) {
			logEntryListRepository = new LogEntriesRepository(context);
		}
		return getInstance();
	}

	public static boolean isInitialized() {
		return logEntryListRepository != null;
	}

	private LogEntriesRepository(Context context) {
		logEntryDbManager = new LogEntryDbManager(context);
		logEntries.addAll(logEntryDbManager.list());
	}

	public LogEntry getLogEntry(int position) {
		return logEntries.get(position);
	}

	public Long saveLogEntry(LogEntry logEntry) {
		Long id = logEntryDbManager.save(logEntry);
		updateLogEntryList();
		return id;
	}

	public void removeLogEntry(LogEntry logEntry) {
		logEntryDbManager.delete(logEntry);
		updateLogEntryList();
	}

	public LogEntry getLogEntry(long id) {
		return logEntryDbManager.get(id);
	}

	private void updateLogEntryList() {
		logEntries.clear();
		logEntries.addAll(logEntryDbManager.list());
	}

	public List<LogEntry> getLogEntries() {
		return logEntries;
	}

}
